#coding = utf-8
#卷积神经网络模型保存
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
testimg = mnist.test.images
testlabel = mnist.test.labels
#NETWORK TOPOLOGIES
n_input = 784
n_output = 10
#NETWORK PARAMETERS
weights = {
    'wc1': tf.Variable(tf.random_normal([3,3,1,64], stddev=0.1)),
    'wc2': tf.Variable(tf.random_normal([3,3,64,128], stddev=0.1)),
    'wd1': tf.Variable(tf.random_normal([7*7*128, 1024], stddev=0.1)),
    'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))
}
bias = {
    'bc1': tf.Variable(tf.random_normal([64], stddev=0.1)),
    'bc2': tf.Variable(tf.random_normal([128], stddev=0.1)),
    'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),
    'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))
}
def conv_basic(_input, _w, _b, _keepratio):
    #INPUT
    _input_r = tf.reshape(_input, shape=[-1,28,28,1])
    #CONV LAYER 1
    _conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1,1,1,1], padding='SAME')
    _conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
    _pool1 = tf.nn.max_pool(_conv1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
    _pool_dr1 = tf.nn.dropout(_pool1, _keepratio)
    #CONV LAYER 2
    _conv2 = tf.nn.conv2d(_pool_dr1, _w['wc2'], strides = [1,1,1,1], padding='SAME')
    _conv2 = tf.nn.relu(tf.nn.bias_add(_conv2, _b['bc2']))
    _pool2 = tf.nn.max_pool(_conv2, ksize=[1,3,3,1], strides=[1,2,2,1], padding='SAME')
    _pool_dr2 = tf.nn.dropout(_pool2, _keepratio)
    #VECTORIZE
    _dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])
    #FULLY CONNECTED LAYER1
    _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))
    _fc_dr1 = tf.nn.dropout(_fc1, _keepratio)
    #FULLY CONNECTED LAYER2
    _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
    #RETURN
    out = {
        'input_r':_input_r, 'conv1':_conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,
        'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,
        'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out
    }
    return out
print("CNN READY")

#INPUTS AND OUTPUTS
x = tf.placeholder("float", [None, 784])
y = tf.placeholder("float", [None, 10])
keepratio = tf.placeholder(tf.float32)
#FUNCTIONS
_pred = conv_basic(x, weights, bias, keepratio)['out']
cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y, 1), logits=_pred))
optm = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost)
_corr = tf.equal(tf.arg_max(_pred, 1), tf.arg_max(y, 1))
accr = tf.reduce_mean(tf.cast(_corr, tf.float32))
init = tf.global_variables_initializer()
#SAVER
#每一个epoch保存一次模型参数
save_step = 1
#max_to_keep 表示保存最近的3次模型参数
saver = tf.train.Saver(max_to_keep=3)

print("GRAPH READY")
#do_train = 1 表示在训练 do_train = 0 表示在测试
do_train = 0
sess = tf.Session()
sess.run(init)

#迭代次数
training_epochs = 15
#每次迭代选择的样本数
batch_size = 16
#展示
display_step = 1
sess = tf.Session()
sess.run(init)
if do_train == 1:
    for epoch in range(training_epochs):
        avg_cost = 0
        #    num_batch = int(mnist.train.num_examples/batch_size)
        num_batch = 10
        for i in range(num_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio: 0.7})
            feeds = {x: batch_xs, y: batch_ys, keepratio: 1.}
            avg_cost += sess.run(cost, feed_dict=feeds) / num_batch
        # DISPLAY
        if epoch % display_step == 0:
            feeds_train = {x: batch_xs, y: batch_ys, keepratio: 1.}
            train_acc = sess.run(accr, feed_dict=feeds_train)
            print("Epoch: %03d/%03d cost: %.9f train_acc: %.3f" % (epoch, training_epochs, avg_cost, train_acc))
        # Save Net
        if epoch % save_step == 0:
            saver.save(sess, "save/nets/cnn_mnist_basic.ckpt-" + str(epoch))
if do_train == 0:
    epoch = training_epochs-1
    saver.restore(sess, "save/nets/cnn_mnist_basic.ckpt-" + str(epoch))
    test_acc = sess.run(accr, feed_dict={x:testimg, y:testlabel, keepratio:1.})
    print("TEST ACCURACY: %.3f" % (test_acc))
print('Done!')
